package com.nopay.cdxphone.ui.ativity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.cdxphone.Constants;
import com.nopay.cdxphone.R;
import com.nopay.cdxphone.base.BaseActivity;
import com.nopay.cdxphone.bean.CommonResponse;
import com.nopay.cdxphone.bean.RegisterImageBean;
import com.nopay.cdxphone.bean.request.RegisterRequest;
import com.nopay.cdxphone.bean.response.GetVerifiCodeResponse;
import com.nopay.cdxphone.databinding.ActivityRegisterBinding;
import com.nopay.cdxphone.net.OkGoUtil;
import com.nopay.cdxphone.net.callback.JsonCallback;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ProjectName: myVisualPhone
 * @Package: cn.cn.myvisualphone.ui.ativity
 * @ClassName: RegisterActivity
 * @Description: 注册Activity
 * @Author: anqi
 * @CreateDate: 2021/5/20 22:25
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/5/20 22:25
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class RegisterActivity extends BaseActivity<ActivityRegisterBinding> {

    private String uuid = "";

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {

        getCaptchaCode();
        binding.rlRoot.setPadding(0, getStatusBarHeight(com.nopay.cdxphone.ui.ativity.RegisterActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSwipeBackHelper.backward();

            }
        });

        binding.loginEtRepwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    checkInput();
                    doRegister();
                    return true;
                }
                return false;
            }
        });
//        binding.tvVerificationCode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String userPhone = binding.loginEtUser.getText().toString().trim();
//                if (!TextUtils.isEmpty(userPhone)) {
//                    if (RegexUtils.isMobileSimple(userPhone)) {
//                        //请求验证码接口
//                        doVerifyCode();
//                        new CountDownTimer(60000, 1000) {
//
//                            @Override
//                            public void onTick(long millisUntilFinished) {
//                                int second = (int) (Math.round((double) millisUntilFinished / 1000) - 1);
//                                binding.tvVerificationCode.setClickable(false);
//                                binding.tvVerificationCode.setText("剩余" + second + "秒");
//
//                            }
//
//                            @Override
//                            public void onFinish() {
//                                binding.tvVerificationCode.setClickable(true);
//                                binding.tvVerificationCode.setText("获取验证码");
//                            }
//                        }.start();
//                    } else {
//                        ToastUtils.showShort(getResources().getString(R.string.please_input_right_phone_number));
//                    }
//
//                } else {
//                    ToastUtils.showShort(getResources().getString(R.string.please_input_phone_number));
//
//                }
//            }
//        });
        binding.ivCaptchaRefresh.setOnClickListener(view -> getCaptchaCode());
        binding.loginEtUser.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                changeRegisterBtn(s);
            }
        });
        binding.etInputCaptcha.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                changeRegisterBtn(s);
            }
        });
        binding.loginEtPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                changeRegisterBtn(s);

            }
        });
        binding.loginEtRepwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String s1 = s.toString();

            }

            @Override
            public void afterTextChanged(Editable s) {
                changeRegisterBtn(s);

            }
        });
        binding.commitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkInput();
                doRegister();
            }
        });
    }

    private void changeRegisterBtn(Editable s) {
        String s1 = s.toString();
        if (!TextUtils.isEmpty(s1)) {
            if (!TextUtils.isEmpty(binding.loginEtUser.getText().toString().trim()) &&
                    !TextUtils.isEmpty(binding.etInputCaptcha.getText().toString().trim()) &&
                    !TextUtils.isEmpty(binding.loginEtPwd.getText().toString().trim()) &&
                    !TextUtils.isEmpty(binding.loginEtRepwd.getText().toString().trim())) {
                binding.commitBtn.setBackgroundResource(R.drawable.normal_login_btn_shape);
                binding.commitBtn.setClickable(true);
            } else {
                binding.commitBtn.setBackgroundResource(R.drawable.unclick_login_btn_shape);
                binding.commitBtn.setClickable(false);
            }
        } else {
            binding.commitBtn.setBackgroundResource(R.drawable.unclick_login_btn_shape);
            binding.commitBtn.setClickable(false);
        }
    }

    /**
     * 获取图片验证吗
     */
    private void getCaptchaCode() {
        OkGoUtil.get(Constants.CAPTCHA_IMAGE_URL, this, null,
                new JsonCallback<RegisterImageBean>(mCurrentActivity) {
                    @Override
                    public void onCustomError(Throwable throwable) {

                    }

                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<RegisterImageBean> response) {
                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
                            uuid = response.body().getUuid();
                            //将Base64编码字符串解码成Bitmap
                            byte[] decodedString = Base64.decode(response.body().getImg(), Base64.DEFAULT);
                            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                            //设置ImageView图片
                            binding.ivCaptchaCode.setImageBitmap(decodedByte);
                        }
                    }
                });
    }

    private void doVerifyCode() {
        String userPhone = binding.loginEtUser.getText().toString().trim();
        api.doGetVerifiCode(userPhone).enqueue(new Callback<GetVerifiCodeResponse>() {
            @Override
            public void onResponse(Call<GetVerifiCodeResponse> call, Response<GetVerifiCodeResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        ToastUtils.showShort(response.body().getMsg());
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<GetVerifiCodeResponse> call, Throwable t) {
                ToastUtils.showShort(com.nopay.cdxphone.ui.ativity.RegisterActivity.this.getResources().getString(R.string.call_api_error));
            }
        });
    }

    private void checkInput() {
        String userPhone = binding.loginEtUser.getText().toString().trim();
        String code = binding.etInputCaptcha.getText().toString().trim();
        String pwd = binding.loginEtPwd.getText().toString().trim();
        String repwd = binding.loginEtRepwd.getText().toString().trim();
        if (TextUtils.isEmpty(userPhone)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_phone_number));
            return;
        }
        if (TextUtils.isEmpty(code)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_code));
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_phone_pwd));
            return;
        }
        if (TextUtils.isEmpty(repwd)) {
            ToastUtils.showShort(getResources().getString(R.string.please_reinput_phone_pwd));
            return;
        }
        if (pwd.length() < 6) {
            ToastUtils.showShort(getResources().getString(R.string.pwd_less_six));
            return;
        }
        if (!pwd.equals(repwd)) {
            ToastUtils.showShort(getResources().getString(R.string.different_pwd));
            return;
        }
        if (!RegexUtils.isMobileExact(userPhone)) {
            ToastUtils.showShort(getResources().getString(R.string.please_input_right_phone_number));
            return;
        }

    }

    private void doRegister() {
        String userPhone = binding.loginEtUser.getText().toString().trim();
        String code = binding.etInputCaptcha.getText().toString().trim();
        String pwd = binding.loginEtPwd.getText().toString().trim();
        String repwd = binding.loginEtRepwd.getText().toString().trim();
        String inviteCode = binding.loginEtInviteCode.getText().toString().trim();
        RegisterRequest request = new RegisterRequest();
        request.setPhone(userPhone);
        request.setVerificationCode(code);
        request.setPassword(pwd);
        request.setRepPassword(repwd);
        request.setInvitationCode(inviteCode);
        request.setUuid(uuid);
        //配置请求对象结束
        RequestBody body = getRequestBody(request);
        api.doRegister(body).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        ToastUtils.showShort(response.body().getMsg());
                        mSwipeBackHelper.backwardAndFinish(LoginActivity.class);
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                ToastUtils.showShort(com.nopay.cdxphone.ui.ativity.RegisterActivity.this.getResources().getString(R.string.call_api_error));
            }
        });
    }

}
